package com.taiyuan.tongcheng.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import im.yixin.algorithm.MD5;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.KJDB;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.CipherUtils;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.StringUtils;
import org.kymjs.kjframe.utils.SystemTool;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import cn.jpush.android.api.JPushInterface;

import com.taiyuan.tongcheng.application.AppConfig;
import com.taiyuan.tongcheng.application.TCBroadcastAction;
import com.taiyuan.tongcheng.bean.UserInfo;
import com.taiyuan.tongcheng.db.TcDbHelper;
import com.taiyuan.tongcheng.http.HTTPFieldConstant;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.util.CommonUtil;
import com.taiyuan.tongcheng.util.L;
import com.taiyuan.tongcheng.util.SharePreferenceUtil;
import com.taiyuan.tongcheng.util.TcUtil;
import com.taiyuan.tongcheng.webservice.Webservice;
import com.taiyuan.tongcheng.widget.LoginStylePopupWindow;
import com.taiyuan.tongcheng.widget.dialog.TcBuilder;
import com.tytc56.user.R;

/**
 * 
 * @Description 登录界面
 * @author wzq
 * @date 2015-7-23 下午7:13:38
 * @update (date)
 * @version V1.0
 */
public class LoginActivity extends BaseActivity implements
		OnFocusChangeListener {

	// 1 wdiget
	@BindView(id = R.id.login_layout_input)
	private RelativeLayout mLayoutInput;
	@BindView(id = R.id.login_et_uid)
	private EditText mEtUid;
	@BindView(id = R.id.login_img_delete, click = true)
	private ImageView phoneDelete;
	@BindView(id = R.id.login_et_pwd)
	private EditText mEtPwd;
	@BindView(id = R.id.login_btn_login, click = true)
	private Button mBtnLogin;
	@BindView(id = R.id.btn_regist, click = true)
	private Button regBtn;
	@BindView(id = R.id.tv_help, click = true)
	private TextView errorTv;

	private LoginStylePopupWindow stylePopupWindow;

	// 2工具
	private SharePreferenceUtil spUtil;

	public static final int LOGIN_OK = 0X01;
	public static final int LOGIN_ERROR_NONAME = 0X02;
	public static final int LOGIN_ERROR_PWD = 0X03;
	public static final int NET_WORK_EROR = 0X04;
    // intentfilter
	private IntentFilter  intentFilter;
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_login);
	}

	@Override
	public void initWidget() {
		super.initWidget();
		initView();
		spUtil = new SharePreferenceUtil(getApplicationContext(),
				AppConfig.SHARE_NAME);
		
//		spUtil.setRegistrationID("sdfs22324324234234s");
		spUtil.setRegistrationID(JPushInterface
				.getRegistrationID(getApplicationContext()));
		initEtUser();
		initPopuWindow();
		initBroadCast();
		topTv.setText(R.string.submit);
		rightTv.setVisibility(View.GONE);
		mEtUid.setOnFocusChangeListener(this);
		mEtPwd.setOnFocusChangeListener(this);

	}

	private void initBroadCast() {
		intentFilter=new IntentFilter();
		intentFilter.addAction(TCBroadcastAction.SUCCESS_LOGIN);
		registerReceiver(receiver, intentFilter);
	}

	private BroadcastReceiver receiver =new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			LoginActivity.this.finish();
		}
	};
	
	
	@Override
	protected void initView() {
		super.initView();
	}

	private void initPopuWindow() {
		stylePopupWindow = new LoginStylePopupWindow(this);
	}

	/**
	 * 
	 * @Description: 初始化用户名密码
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-6-29 下午6:57:10
	 * @update (date)
	 */
	private void initEtUser() {
		if (StringUtils.isEmpty(mEtUid.getText())) {
			phoneDelete.setVisibility(View.GONE);
		} else {
			phoneDelete.setVisibility(View.VISIBLE);
		}

		mEtUid.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (StringUtils.isEmpty(mEtUid.getText())) {
					phoneDelete.setVisibility(View.GONE);
				} else {
					phoneDelete.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
	}

	

	
	
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.login_btn_login:
			logIn();
	//      startActivity(new Intent(LoginActivity.this,MainActivitySlide.class));
//			startActivity(new Intent(LoginActivity.this,PayActivity.class));
			break;
		case R.id.login_img_delete:
			mEtUid.setText(null);
			break;
		case R.id.btn_regist:
			startActivity(new Intent(this, RegActivity.class));
			// startActivity(new Intent(this,ProgressActivity.class));
			break;
		case R.id.tv_help:
			stylePopupWindow.showAtLocation(errorTv, Gravity.BOTTOM, 0, 0);
			break;
		}
	}

	/**
	 * 输入合法性检测
	 */
	private boolean inputCheck() {
		
		if (StringUtils.isEmpty(mEtUid.getText().toString())) {
			showErroCustomToast(getString(R.string.account_not_empty));
			return false;
		}
		if (StringUtils.isEmpty(mEtPwd.getText().toString())) {
			showErroCustomToast(getString(R.string.password_not_empty));
			return false;
		}
		
		if(!SystemTool.checkNet(getApplicationContext())){
			showErroCustomToast(getString(R.string.net_work_error));
			return false;
		}
		return true;
	}

	/**
	 * 
	 * @Description: 登录方法
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-7-23 下午7:57:09
	 * @update (date)
	 */
	private void logIn() {

		if (!inputCheck()) {
			return;
		}
		TcLoaddingDialog.show();
		long time = System.currentTimeMillis();
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjh = new KJHttp(config);
		HttpParams params = new HttpParams();
		params.put(HTTPFieldConstant.POST_PARAMS_COMMON_ACT,
				TcUtil.getApiName(TcWebservice.API.ACCOUNT_LOGIN_PWD));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_MOBILE, mEtUid
				.getText().toString());
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_PWD, mEtPwd.getText()
				.toString());
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_FROM, "1");
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_DEVID,
				CommonUtil.getAndroidDeviceUnique(this));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_VER,
				SystemTool.getAppVersionCode(this));
//		if(spUtil.getRegistrationID().length()>3){
//			params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_REGISTRATIONID,
//					spUtil.getRegistrationID());
//		}else{
//			params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_REGISTRATIONID,
//					JPushInterface.getRegistrationID(this));
//		}
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_REGISTRATIONID,
				JPushInterface.getRegistrationID(this));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_TM, time + "");
		params.put(
				HTTPFieldConstant.POST_PARAMS_ACCOUNT_SIGN,
				CipherUtils.md5(mEtUid.getText().toString()
						+ mEtPwd.getText().toString() + "1"
						+ CommonUtil.getAndroidDeviceUnique(this)
						+ SystemTool.getAppVersionCode(this)
						+ (spUtil.getRegistrationID().length()>3?spUtil.getRegistrationID():JPushInterface.getRegistrationID(this)) + time
						+ TcWebservice.signSecretKey));
		KJLoger.debug("URL="
				+ TcWebservice.WEBSERVER_IP
				+ TcWebservice.API.ACCOUNT_LOGIN_PWD
				+ "参数:"
				+ "**"
				+ HTTPFieldConstant.POST_PARAMS_COMMON_ACT
				+ "="
				+ TcUtil.getApiName(TcWebservice.API.ACCOUNT_LOGIN_PWD)
				+ "**"
				+ HTTPFieldConstant.POST_PARAMS_ACCOUNT_MOBILE
				+ "="
				+ mEtUid.getText().toString()
				+ "**"
				+ HTTPFieldConstant.POST_PARAMS_ACCOUNT_PWD
				+ "="
				+ mEtPwd.getText().toString()
				+ "**"
				+ HTTPFieldConstant.POST_PARAMS_ACCOUNT_FROM
				+ "="
				+ "1"
				+ "**"
				+ HTTPFieldConstant.POST_PARAMS_ACCOUNT_DEVID
				+ "="
				+ CommonUtil.getAndroidDeviceUnique(this)
				+ "**"
				+ HTTPFieldConstant.POST_PARAMS_ACCOUNT_VER
				+ "="
				+ SystemTool.getAppVersionCode(this)
				+ "**"
				+ HTTPFieldConstant.POST_PARAMS_ACCOUNT_REGISTRATIONID
				+ "="
				+ JPushInterface.getRegistrationID(this)
				+ "**"
				+ HTTPFieldConstant.POST_PARAMS_ACCOUNT_TM
				+ "="
				+ time
				+ ""
				+ "**"
				+ HTTPFieldConstant.POST_PARAMS_ACCOUNT_SIGN
				+ "="
				+ CipherUtils.md5(mEtUid.getText().toString()
						+ mEtPwd.getText().toString() + "1"
						+ CommonUtil.getAndroidDeviceUnique(this)
						+ SystemTool.getAppVersionCode(this)
						+ JPushInterface.getRegistrationID(this) + time
						+ TcWebservice.signSecretKey)
			

		);
		kjh.post(
				TcWebservice.WEBSERVER_IP + TcWebservice.API.ACCOUNT_LOGIN_PWD,
				params, new HttpCallBack() {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);

						String str;
						try {
							str = URLDecoder.decode(new String(t), "UTF-8");
							KJLoger.debug(str);
							WebData webData = TcJsParser.getWedataData(str);
							
							if (webData.getStatus() == 1) {
								UserInfo info = TcJsParser.getUserInfo(webData
										.getData());
								TcDbHelper.saveUser(LoginActivity.this, info);
								spUtil.setLoginFlag(1);
								GotoMain();
								showCustomToast(webData.getMsg());
							} else {
								showCustomToast(webData.getMsg());
							}
							if (TcLoaddingDialog.isShowing()) {
								TcLoaddingDialog.cancel();
							}
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}

					}

					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);
						if (errorNo == -1) {
							if (TcLoaddingDialog.isShowing()) {
								TcLoaddingDialog.cancel();
							}
							// 网络超时
							showErroCustomToast(strMsg);
						}
					}
				});
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {

		switch (v.getId()) {
		case R.id.login_et_uid:
			if (hasFocus) {
				if (StringUtils.isEmpty(mEtUid.getText())) {
					phoneDelete.setVisibility(View.GONE);
				} else {
					phoneDelete.setVisibility(View.VISIBLE);
				}
			} else {
				phoneDelete.setVisibility(View.GONE);
			}

			break;

		default:
			break;
		}

	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}

}
